<?php

namespace AppBundle\Form;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class UserType extends AbstractType
{
    private $_em;

    public function __construct(\Doctrine\Common\Persistence\ObjectManager $em)
    {
        $this->_em = $em;
    }
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        /** @var  $user User*/
        $user = $options['data'];
        $builder
            ->add('username',null,[
                'constraints'=>[
                    new Constraints\Callback([
                        'callback'=> function($object,ExecutionContextInterface $context) use($user){
                            $qb = $this->_em->getRepository('AppBundle:User')->createQueryBuilder('u')
                                ->where('u.username = :username')
                                ->setParameters(['username'=>$user->getUsername()])
                                ;
                            if($user->getId()){
                                $qb->andWhere('u.id <> :id')->setParameter('id',$user->getId());
                            }
                            $res = $qb->getQuery()->getOneOrNullResult();
                            if($res){
                                $context->addViolation('用户名已存在');
                            }
                        }
                    ])
                ]
            ])
            ->add('password')
            ->add('name')
            ->add('mobile')
            ->add('phone')
            ->add('email')
            ->add('sex',ChoiceType::class,[
                'expanded'=>'true',
                'choices'=>[
                    '男'=>'男',
                    '女'=>'女',
                ]
            ])
            ->add('duty')
            ->add('departId')
            ->add('roleId')
            ->add('onJob',ChoiceType::class,[
                'expanded'=>'true',
                'choices'=>array_flip(User::dropdown('on_job')),
            ])
            ->add('startAt')
            ->add('unitStartAt')
        ;
    }
    
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\User',
            'translation_domain'=>'app',
        ));
    }
}
